<template>
    <div>
      <h2>WebSocket 测试</h2>
      
      <!-- 显示从服务器收到的消息 -->
      <p>服务器消息：{{ message }}</p>
      
      <!-- 输入框，用于输入要发送的消息 -->
      <input v-model="inputMessage" placeholder="输入消息" />
      
      <!-- 按钮，用于发送消息 -->
      <button @click="sendMessage">发送消息</button>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onUnmounted } from 'vue'
  
  const ws = ref(null)            // WebSocket 实例
  const message = ref('未收到消息') // 显示从服务器接收到的消息
  const inputMessage = ref('')     // 用户输入的消息
  
  // 建立 WebSocket 连接
  onMounted(() => {
    ws.value = new WebSocket('https://192.168.31.150:8443/hmi/tedge/tagbook')
  
    ws.value.onopen = () => {
      console.log('WebSocket 连接已打开')
    }
  
    ws.value.onmessage = (event) => {
      console.log('收到服务器消息:', event.data)
      message.value = event.data  // 将接收到的消息显示到界面上
    }
  
    ws.value.onerror = (error) => {
      console.error('WebSocket 发生错误:', error)
    }
  
    ws.value.onclose = () => {
      console.log('WebSocket 连接已关闭')
    }
  })
  
  // 发送消息到服务器
  const sendMessage = () => {
    if (ws.value && ws.value.readyState === WebSocket.OPEN) {
      ws.value.send(inputMessage.value)  // 发送输入框中输入的消息
      console.log('已发送消息:', inputMessage.value)
    } else {
      console.error('WebSocket 未连接')
    }
  }
  
  // 组件卸载时关闭 WebSocket 连接
  onUnmounted(() => {
    if (ws.value) {
      ws.value.close()
    }
  })
  </script>
  
  <style scoped>
  h2 {
    color: #42b983;
  }
  input {
    padding: 5px;
    margin-right: 10px;
    border-radius: 4px;
    border: 1px solid #ccc;
  }
  button {
    padding: 5px 10px;
    background-color: #42b983;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }
  button:hover {
    background-color: #339966;
  }
  </style>
  